package jsu.yym.tiktok.config;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jsu.yym.tiktok.pojo.LoginUser;
import jsu.yym.tiktok.server.JwtUtil;
import jsu.yym.tiktok.server.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        //判断是否携带token
        if (!StringUtils.hasText(token)) {
            System.out.println("11111");
            // 如果没有 token，获取前端请求路径
            String requestURI = request.getRequestURI();
            System.out.println(requestURI);
            if (requestURI.startsWith("/user/") || requestURI.equals("/video/get/hot")||
                    requestURI.startsWith("/video/get/share")) {
                System.out.println("2222");
                // 如果请求路径需要匿名访问，可以直接放行
                filterChain.doFilter(request, response);
            } else {
                response.setStatus(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
            }
            return ;
        }
        System.out.println("222"+token);
        //解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token出错");
        }
        //从redis中获取对象信息
        String redisKey = "login:" + userId;
        LoginUser user = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户未登录");
        }
        System.out.println(user.toString());
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        System.out.println("用户权限信息设置成功");
        filterChain.doFilter(request, response);
    }

}
